
<?php

/**
 * PHP versions 4 and 5
 * MagicPHP
 * Licensed under The Open Group Test Suite License
 * Redistributions of files must retain the above copyright notice.
 * @copyright     Copyright 2011
 * @link
 * @package       Model
 * @since         MaginPHP 1.0
 * @license
 */
?>
<?php
/**
 * @author: aNKIT kHAMBHATA
 * @desc: Paging Function Class
 */
class Magic_Paging_Model {

    /**
     * @author: aNKIT kHAMBHATA
     * @desc: Get the total numbers of Id from the table and use to set paging link
     * @param $sql: mysql query
     * @param $id_m: primary key name of table
     */
    protected function toralRecordSet($sql, $id_m) {
        $result = mysql_query($sql);
        $num = @mysql_num_rows($result);
        $id = array();
        $i = 0;
        while ($row = @mysql_fetch_assoc($result)) {
            $id[$i] = $row[$id_m];
            $i++;
        }
        return $id;
    }
    protected function getWhereID($start,$end,$id,$record_per_page,$total) {
        $p_total = $start + $record_per_page;
        if ($start == '') {
            $start = 0;
        }
        if ($p_total < $total) {
            $End = $p_total;
        } else {
            $End = $total;
        }
        $s_id = '';
        for ($i = $start; $i < $End; $i++) {
            if ($s_id == '') {
                $s_id.="'" . $id[$i] . "'";
            } else {
                $s_id.=",'" . $id[$i] . "' ";
            }
        }
        return $s_id;
    }

    /**
     * @author: aNKIT kHAMBHATA
     * @desc: Get the Particular numers of dataset form the total numbers of data
     * @param: $start: value of id from where records start
     * @param: $end: value of id from where records ends
     * @param: $table: table name
     * @param: $id: collection of set of records id
     * @param: $primaryKey: name of primary key of table
     * @param: $extra: extra condition that we have to add into quer y
     * @param: $type: type of query from 0-4
     * @param: $record_per_page: numbers of records per page
     * @param: $total: total numbers of records
     * @param: $fields: names of fields which we have to fetch from the database
     * @param: $OrderBY: starus of order by
     * @param: $Order: status of order (Accending /Desending )
     */
    protected function pageRecoredSet($start, $end, $table, $id, $primaryKey, $wherecondition, $type, $record_per_page, $total, $fields, $OrderBY, $Order) {

        if (!empty($fields)) {
            $fields = $fields;
        } else {
            $fields = "*";
        }
        $s_id = '';
        
        $p_total = $start + $record_per_page;
        if ($start == '') {
            $start = 0;
        }
        if ($p_total < $total) {
            $End = $p_total;
        } else {
            $End = $total;
        }
        for ($i = $start; $i < $End; $i++) {
            if ($s_id == '') {
                $s_id.="'" . $id[$i] . "'";
            } else {
                $s_id.=",'" . $id[$i] . "' ";
            }
        }
        
        /**
         * @desc:This is the simple query without join.
         * This is basically built query for single table 
         * @example: select field1,field2 from talbe where tid IN(1,2,3) order by tid ASC ;
         */
        if ($type == '0') { 
            $sql = "SELECT " . @implode(',', $fields) . "  FROM " . $table . " where " . $primaryKey . "  IN  (" . $s_id . ") " . $wherecondition . " " . $OrderBY . " " . $Order;
        }
        /**
         * @desc: This query is used to generate some disting data from database 
         * @example:select DISTICT field1 from talbe where tid IN (1,2,3) order by tid ASC
         */
        else if ($type == '1') {
            $sql = "SELECT DISTINCT  " . $wherecondition . " from  " . $table . " where " . $primaryKey . "  IN  (" . $s_id . ") " . $OrderBY . " " . $Order;
        }
        /**
         * @desc: This query type is used for simple join of tables .
         * @example: select t1.field1,t2.field2 from t1,t2 where  t1.t1id IN (1,2,3) && t1.t1id = t2.t1id  order by t1.t1id ASC
         */
        else if ($type == '2') {
            $tables = explode(",", $table);
            $sql = "SELECT " . implode(',', $fields) . " FROM " . $table . " where " . $primaryKey . "  IN  (" . $s_id . ") " . $wherecondition . " " . $OrderBY . " " . $Order;
        }
        /**
         * @desc :  This type is prefered where you used JOIN syntaxt into query .
         * JOIN cam be any join .Like JOIN ,LEFT JOIN ,RIGHT JOIN 
         * @example : select t1.field1, t2.field1 from t1 JOIN/LEFT JOIN /RIGHT JOIN  t2 ON (t1.id = t2.id) where t1.id IN (1,2,4) ORDER BY ta.id ASC ;
         */
        else if ($type == 3) {
            $tables = explode(",", $table);
            $sql = "SELECT " . @implode(',', $fields) . " FROM " . $table . "  " . $wherecondition . " where " . $primaryKey . "  IN  (" . $s_id . ")  " . $OrderBY . " " . $Order;
        } 
        /**
         * @desc : This type is also used for when you used JOIN syntaxt in your query .
         * Only difference is ,you no need to mention fileds of table because it take all the
         * fields from all the talbe that you use for joining .
         * @example : select * from t1 JOIN / LEFT JOIN / RIGHT JOIN t2 ON (t1.id = t2.id ) && t1.id IN (1,2,3,4) order by t1.id asc ;
         */
        else if ($type == 4) {
            $sql = "select * from " . $table . "  " . $wherecondition . " where " . $primaryKey . "  IN  (" . $s_id . ")  " . $OrderBY . " " . $Order;
        }
        $record = mysql_query($sql);
        echo $sql ; 
        return $record;
    }

    protected function pageState($total_no_record, $record_per_page, $link_per_page, $start) {
        $ans = array();
        //$total_no_record=count($this->Database($query,$w_id));//this is the public function that count the total no of rows
        $current_page = ceil($start / $record_per_page) + 1;
        //echo "currentpage=".$current_page."<br/>";
        $total_no_page = ceil($total_no_record / $record_per_page);
        $side = $link_per_page * $record_per_page;
        $ans["tot_record"] = $total_no_record;
        $ans["side"] = $side;
        $ans["cureentpage"] = $current_page;
        return $ans;
    }

    /**
     * @author: aNKIT kHAMBHATA
     * @desc: this function is set middle link of the paging
     * @param: $sql: query
     * @param: $thispage: page url
     * @param: $start: value of primary key from where display records start
     * @param: $record_per_page: number s of records per page
     * @param: $no_of_link: nubmers of link per page
     * @param: $w_id: primary key of table
     * @param: $extra: extra parameter that we have to pass into url
     */
    public function middleLink($total_no_record, $thispage, $start, $record_per_page, $no_of_link, $extra) {
        $link_array = array();
        $data = $this->pageState($total_no_record, $record_per_page, $no_of_link, $start);
        if (empty($start)) {
            $start = 0;
        }
        $j = 1;
        $current_page = ceil($start / $record_per_page) + 1;
        for ($i = 0; $i < $data["tot_record"]; $i+=$record_per_page) {
            if (($i > ($start - $data["side"])) && ($i < ($start + $data["side"]))) {
                if ($current_page == $j) {
                    $link_array[] = "<strong >" . $j . "</strong>";
                } else {
                    $str1 = '<a href="' . $thispage . ($i > 0 ? ("&start=") . $i : "&start=0") . $extra . '"';
                    $str2 = 'title="' . $j . '">' . $j;
                    $str3 = '</a>';
                    $link_array[] = $str1 . $str2 . $str3;
                }
            }
            $j++;
        }

        return implode("", $link_array);
    }

    /**
     * @author: aNKIT kHAMBHATA
     * @desc: this function is set next link of the paging
     * @param: $thispage: page url
     * @param: $start: value of primary key from where display records start
     * @param: $record_per_page: number s of records per page
     * @param: $no_of_link: nubmers of link per page
     * @param: $w_id: primary key of table
     * @param: $extra: extra parameter that we have to pass into url
     */
    public function nextLink($thispage, $start, $total_no_record, $reocrd_per_page, $extra) {
        $str = '';
        if (empty($start)) {
            $start = 0;
        }
        if ($start + $reocrd_per_page < $total_no_record) {
            $str = '<a href="' . $thispage . ("&start=" . max(0, $start + $reocrd_per_page)) . $extra . '" title="Next Page">Next</a>';
        }
        return $str;
    }

    /**
     * @author: aNKIT kHAMBHATA
     * @desc: this function is set previous  link of the paging
     * @param: $thispage: page url
     * @param: $start: value of primary key from where display records start
     * @param: $record_per_page: number s of records per page
     * @param: $no_of_link: nubmers of link per page
     * @param: $w_id: primary key of table
     * @param: $extra: extra parameter that we have to pass into url
     */
    public function previousLink($thispage, $start, $total_no_record, $reocrd_per_page, $extra) {
        $str = '';
        if (empty($start)) {
            $start = 0;
        }
        if (($start - $reocrd_per_page) >= 0) {
            $next = $start - $reocrd_per_page;
            $str = '<a href="' . $thispage . ($next > 0 ? ("&start=") . $next : "") . $extra . '" title="Previous Page">Previous</a>';
        }
        return $str;
    }

    /**
     * @author: aNKIT kHAMBHATA
     * @desc:  Generate Order By ids for search in admin panel
     * @param $join_status: 1/0
     * @param $table_name: name of table
     */
    protected function createOrderAndIds($join_status, $table_name, $primarykey) {
        $OrderBy = '';
        $w_id = '';
        $segment_arr = array();
        $segment = '';
        $datas = array();
        if ($join_status == 1) {
            $tables = explode(",", $table_name);
            $OrderBy = "ORDER BY " . $tables[0] . "." . $primarykey;
            $w_id = $primarykey;
        } else {
            $OrderBy = "ORDER BY " . $primarykey;
            $w_id = $primarykey;
        }
        $datas["orderby"] = $OrderBy;
        $datas["w_id"] = $w_id;
        return $datas;
    }

    /**
     * @author: aNKIT kHAMBHATA
     * @desc:  Generate Order By ids for search in admin panel
     * @param: $Order: ASC/DESC
     * @param $SortOrder: 1/0
     */
    protected function setOrder($Order, $SortOrder, $start) {

        $SetOrder = '';
        if ($Order == '') {
            $SetOrder = 'DESC';
        } else if ($Order == 'ASC' && isset($SortOrder) && $SortOrder == '') {
            $SetOrder = 'DESC';
        } else if ($Order == 'ASC' && isset($SortOrder) && $SortOrder == '1') {
            $SetOrder = 'DESC';
        } else if ($Order == 'DESC' && isset($SortOrder) && $SortOrder == '') {
            $SetOrder = 'ASC';
        } else if ($Order == 'DESC' && isset($SortOrder) && $SortOrder == '1') {
            $SetOrder = 'ASC';
        }
        return $SetOrder;
    }
    /**
     * @author: aNKIT kHAMBHATA
     * @desc: Create Time stamp from give date
     * @param: $sign: from which we saperate the date
     * @param: $date: value of date
     */
    protected function makeTimestamp($sign, $date) {
        $dt = explode($sign, $date);
        return mktime(0, 0, 0, $dt[0], $dt[1], $dt[2]);
    }
    /**
     * @author: aNKIT kHAMBHATA
     * @desc: Generate Query for master page into admin panel
     * @param: $table_name: name of table
     * @param: $fields: name of filed which you want to display into listing
     * @param: $where_condition: condition ex: is_active =0 && is_delete=0
     * @param: $joining_status: if data fetch from multiple table than its status 1
     * @param: $key: name of field from which we make search
     * @param: $keyword: value of key which used to search from the database
     * @param: $OrderBy: name of the field from which we set order by
     * @param: $Order: asc/desc
     * @param: $search: extra parameter
     * @param: $date1: value of date 1
     * @param: $date2: value of date 2
     * @param: $usedJoinSyntaxt: if we used left join into query than 1 else 0
     */
    protected function queryGenerator($table_name, $fields, $before_where_condition,$after_where_condition, $joining_status, $key, $keyword, $OrderBy, $Order, $search, $date1, $date2, $primaryKey ,$extraCondition ,$limit) {
        $keyline = '';
        $timequery = '';
        if(is_array($fields)){
            $extractField = implode(',', $fields);
        } else {
            $extractField = " * " ;
        }
        $limitString = "";
        if($limit != '') {
            $limitString = $limit ;
        }
        if (isset($key) && $key != '') {
                $keyline = "&& " . trim($key) . "  LIKE '%" . trim($_REQUEST["keyword"]) . "%'";
            }
            if (isset($date1) && $date1 != "") {
                $timequery = '&& unix_timestamp(created_on) BETWEEN  ' . $this->makeTimestamp("/", $date1) . ' AND   ' . $this->makeTimestamp("/", $date2);
            }
        if ($joining_status == '0') {
            //$sql_1 = "select * from " . $table_name . "  where 1=1  " . $keyline . " " . $where_condition . "  " . $extraCondition . "  " . $timequery . " " . $primaryKey;
            $sql = Magic_CURD_Model::callMethod()
            ->defineTable($table_name)
            ->where(" $before_where_condition 1=1  $keyline $after_where_condition $limitString $extraCondition  $timequery  $primaryKey")
            ->selectall()
            ->debug(false);
        } else {
            //$tables = explode(",", $table_name);
            //$sql = "SELECT $extractField FROM   $table_name $before_where_condition WHERE  1=1  $after_where_condition  $keyline  $extraCondition $timequery  $OrderBy  $Order ";
            $sql = Magic_CURD_Model::callMethod()
            ->defineTable($table_name)
            ->where(" $before_where_condition 1=1 $limitString  $keyline $after_where_condition $extraCondition  $timequery  $OrderBy $Order")
            ->selectfield($fields)
            ->debug(false);
//            if ($usedJoinSyntaxt == '1') {
//                $sql = "SELECT " . implode(',', $fields) . " FROM  $table_name $before_where_condition  $keyline $extraCondition $timequery  WHERE 1=1  $after_where_condition  $OrderBy  $Order ";
//            } else {
//                echo "herr"; 
//           
//            }
        }
        if($limitString != '') 
            return Magic_CURD_Model::callMethod()
                    ->coustomBuiltQuery($sql)
                    ->execute();
        else 
            return $sql ;
    }

    /**
     * @author: aNKIT kHAMBHATA 
     * @desc: This is admin side function which create search panel in admin master page
     * @param: $field: array of field
     * @param: $fieldname: array of name of fields
     * @param: $value: instant time selected value
     * @param: $interval: name of interval ex: all,today/yesterday/this month / last month
     * @param: $date1: value of date 1
     * @param: $date2: value of data 2
     */
    public function searchToolBar($field, $fieldname, $value, $interval, $date1, $date2) {
        $arr = array('all', 'today', 'yesterday', 'thismonth', 'lastmonth');
        $str1 = "all,today,yesterday,thismonth,lastmonth";
        $arrtitle = array("ALL", "Today", "Yesterday", "This Month", "Last Month");
        $str = "<script>
		$(function() {
                    $('#date1').datepicker();
                    $('#date2').datepicker();
		});
		</script>
		Date1:<input type='text' name='date1' value='" . $date1 . "' id='date1' /> &nbsp;Date2:<input type='text' value='" . $date2 . "'  name='date2' id='date2' />";
        $str.="<select name='interval' id='interval' onchange='DateGenerator();'>";
        for ($j = 0; $j < count($arr); $j++) {
            if (@strstr($arr[$j], $interval)) {
                $str.='<option value="' . $arr[$j] . '" selected="selected" >' . $arrtitle[$j] . '</option>';
            } else {
                $str.='<option value="' . $arr[$j] . '" >' . $arrtitle[$j] . '</option>';
            }
        }
        $str.="</select>";
        $str.='<select class="search_drop" name="key"><option value="">--Select--</option>';
        for ($i = 0; $i < count($field); $i++) {
            if ($value == $field[$i]) {
                $str.='<option value="' . $field[$i] . '" selected="selected">' . $fieldname[$i] . '</option>';
            } else {
                $str.='<option value="' . $field[$i] . '" >' . @$fieldname[$i] . '</option>';
            }
        }
        $str.='</select>
		<input type="text" value="' . @$_REQUEST["keyword"] . '" name="keyword" id="keyword" />
		<button id="filterbtn" type="submit" title="Save" class="buttonbar">Filter</button>';
        return $str;
    }

    /**
     * @author: aNKIT kHAMBHATA
     * @desc: This is admin side function which create search panel in admin master page
     * @param: $value: value of number that show into per page
     */
    protected function recordsPerPage($value) {
        $field = array(5, 10, 25, 50, 100, 500);
        $str = 'Record per page: <select class="search_drop" name="numofrecord" id="numofrecord" onchange="javascript:myform.submit();">';
        for ($i = 0; $i < count($field); $i++) {
            if ($value == $field[$i]) {
                $str.='<option value="' . $field[$i] . '" selected="selected">' . $field[$i] . '</option>';
            } else {
                $str.='<option value="' . $field[$i] . '" >' . $field[$i] . '</option>';
            }
        }
        $str.='</select>';
        return $str;
    }

    /**
     * @author: aNKIT kHAMBHATA
     * @desc: This is used to add extralink in paggin
     * @param $condition: link text with condition
     */
    public function pushLink($array, $condition) {
        @array_push($array["extraLink"] = $condition);
        return ($array);
    }

    /**
     * @author: aNKIT kHAMBHATA
     * @desc: This is used to add extra Url parameter
     * @param $condition: link text with condition
     */
    public function pushExtraUrlPara($array, $condition) {
        array_push($array["extraUrlPara"] = $condition);
        return $this ; 
        //return ($array);
    }

    /**
     * @author: aNKIT kHAMBHATA
     * @desc: This is used to add extra column in pagin
     * @param $extraColumnArray:array of extra column
     * @param $field : field array 
     * @param $title : title array
     */
    public function pushExtraColumn($extraColumnArray, $field, $title) {
        $referenceElement = array();
        $newElement = array();
        $referenceElementTitle = array();
        $newElementTitle = array();
        for ($i = 0; $i < count($extraColumnArray); $i++) {
            $referenceElement[] = $extraColumnArray[$i]["cAfterField"];
            $newElement[] = $extraColumnArray[$i]["cName"];
            $referenceElementTitle[] = $extraColumnArray[$i]["cAfterTitle"];
            $newElementTitle[] = $extraColumnArray[$i]["cTitle"];
        }
        $resultField = Magic_Common_Model::pushElementInArray($field, $referenceElement, $newElement);
        $resultTitle = Magic_Common_Model::pushElementInArray($title, $referenceElementTitle, $newElementTitle);
        $extraColumn = $newElement;
        $extraTitle = $newElementTitle;
        return array("field" => $resultField, "title" => $resultTitle, "extraColumnField" => $extraColumn, "extraTitle" => $extraTitle);
    }

    /**
     * @author: aNKIT kHAMBHATA
     * @desc: This is used to give all name of column  of tables
     * @param $tables : names of table in coma seperation
     */
    public function arrayOfTableColumn($tables) {
        $table = explode(",", $tables);
        $fieldArray = array();
        $field = array();
        for ($i = 0; $i < count($table); $i++) {
            $sql = "SHOW COLUMNS FROM $table[$i] ";

            $res = mysql_query($sql);
            while ($data = @mysql_fetch_assoc($res)) {
                $field[] = $data["Field"];
            }
            @array_push($fieldArray[$table[$i]] = $field);
            $field = '';
        }
        return $fieldArray;
    }

    /**
     * @author: aNKIT kHAMBHATA
     * @desc: This is used multisearch Condition
     * @param $postArr : $_POST array
     * @param $joinStatus: 1/0
     * @param $table : name of tables in comma seperation
     * @param $tableDisplayField : array of field
     */
    public function multiSearchCondition($postArr, $joinStatus, $table, $tableDisplayField) {
        for ($k = 0; $k < count($tableDisplayField); $k++) {
            if (isset($postArr[$tableDisplayField[$k]]) && $postArr[$tableDisplayField[$k]] != '') {
                if ($joinStatus == 1) {
                    $tableField = $this->arrayOfTableColumn($table);
                    $eArr = Magic_Common_Model::inMultiDimentionArray($tableDisplayField[$k], $tableField);
                    if ($eArr["result"] == 1) {
                        $extraCondition .=" &&  " . $eArr['position'] . "." . $tableDisplayField[$k] . " LIKE '%" . $postArr[$tableDisplayField[$k]] . "%'";
                    }
                } else {
                    $extraCondition .=" &&  " . $tableDisplayField[$k] . " LIKE '%" . $postArr[$tableDisplayField[$k]] . "%'";
                }
            }
        }
        return $extraCondition;
    }
    /**
     * @desc : User to run php code
     * @param type $arg 
     */
    public function magicEval($evalStr){
          eval("\$evalStr = \"$evalStr\";");
          return $evalStr;
    }
}

//End Of Class
?>
